package com.xxx.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

/**
 * controller基类
 * 
 * 
 * 
 */
public abstract class BaseController {

	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	public static final String USER_ID = "userId";	// 用户ID
	
	// 用户ID验证码cookie名称
	private static final String COOKIE_NAME_USERID = "userId";
	// 用户ID验证码过期时间
	private static final int EXPIRE_TIME_USERID = 60 * 30; // 30分钟
	
	/**
	 * 往cookie里设置用户ID
	 */
	public void setUserIdIntoCookie(HttpServletResponse response, String userId) {
		logger.info("enter method setUserIdIntoCookie().");
    	Cookie cookie = new Cookie(COOKIE_NAME_USERID, userId);
        cookie.setMaxAge(EXPIRE_TIME_USERID); 	// 设置会话生命周期为30分钟
        cookie.setHttpOnly(true); 				// httpOnly为true
        response.addCookie(cookie);
        logger.info("setUserIdIntoCookie success");
	}

	/**
	 * 从cookie里获取用户ID
	 */
	public String getUserIdFromCookie(HttpServletRequest request) {
		logger.info("enter method getUserIdFromCookie().");
		Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            if(COOKIE_NAME_USERID.equals(cookie.getName())){
                logger.info("getUserIdFromCookie success");
            	return cookie.getValue();
            }
        }
        logger.info("getUserIdFromCookie fail");
		return null;
	}

	/**
	 * 从request里获取用户ID
	 */
	public String getUserIdFromRequest(HttpServletRequest request) {
		logger.info("enter method getUserIdFromRequest().");
		Object userId = request.getAttribute(USER_ID);
		if(userId==null) {
			logger.error("getUserIdFromRequest fail");
			return null;
		}
		return (String)userId;
	}

	/**
	 * 跳转404错误页面
	 * 
	 * @return ModelAndView 抛出视图
	 */
	public ModelAndView errorView() {
		return new ModelAndView("/error/404.html");
	}

	/**
	 * 跳转无权限访问错误页面
	 * 
	 * @return ModelAndView 抛出视图
	 */
	public ModelAndView notAllowedView() {
		return new ModelAndView("/error/notAllow.html");
	}
	
	/**
	 * 接收请求参数（不带密码）
	 * @param request
	 * @return
	 */
	public String receivePost(HttpServletRequest request) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			String reqBody = sb.toString();
			return URLDecoder.decode(reqBody, "UTF-8");
		} catch (Exception e) {
			logger.error("receivePost 发生异常," + e.getMessage(), e);
		}
		
		return "";
	}
	
	/**
	 * 接收请求参数（带密码）
	 * @param request
	 * @return
	 */
	public String receivePostWithPass(HttpServletRequest request) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			return sb.toString();
		} catch (Exception e) {
			logger.error("receivePostWithPass 发生异常," + e.getMessage(), e);
		}
		
		return "";
	}

}
